(function(){

var templates = [ 
	"leftside_text",
	"rightside_text",
	"task_text",
	"progress_text"
];

function defaults(obj, std){
	for (var key in std)
		if (!obj[key])
			obj[key] = std[key];
	return obj;
}

function mark_columns(base){
	var columns = base.config.columns;
	if (columns)
		for (var i = 0; i < columns.length; i++) {
			if (columns[i].template)
				columns[i].$template = true;
	}
}

/*
	gantt.exportToPDF({
		name:"mygantt.pdf",
		header:"<h1>My company</h1>",
		footer:"<h4>Bottom line</h4>",
		locale:"en",
		start:"01-04-2013",
		end:"11-04-2013",
		skin:'terrace',
		data:{ }
	});
*/
gantt.exportToPDF = function(config){
	config = defaults((config || {}), { 
		name:"gantt.pdf",
		data:this.serialize(),
		config:gantt.config
	});
	this._send_to_export(config);
}

gantt.exportToPNG = function(config){
	config = defaults((config || {}), { 
		name:"gantt.png",
		data:this.serialize(),
		config:gantt.config
	});
	this._send_to_export(config);
}

gantt._send_to_export = function(base){
	mark_columns(base);
	var form = this._create_hidden_form();
	form.firstChild.action = "https://export.dhtmlx.com/gantt";
	form.firstChild.firstChild.value = JSON.stringify(base);
	form.firstChild.submit();
}

gantt._create_hidden_form = function(){
	if (!this._hidden_export_form){
		var t = this._hidden_export_form = document.createElement("div");
		t.style.display = "none";
		t.innerHTML = "<form method='POST'><input type='text' name='data'></form>";
		document.body.appendChild(t);
	}
	return this._hidden_export_form;
}

//patch broken json serialization in gantt 2.1
gantt.json._copyObject = function(obj){
	var copy = {};
	for (var key in obj){
		if (key.charAt(0) == "$")
			continue;
		copy[key] = obj[key];
	}
	copy.start_date = gantt.templates.xml_format(copy.start_date);
	if (copy.end_date)
		copy.end_date = gantt.templates.xml_format(copy.end_date);


	//serialize all text templates
	for (var i = 0; i < templates.length; i++){
		var template = gantt.templates[templates[i]];
		if (template)
			copy["$"+i]	= template(obj.start_date, obj.end_date, obj);
	}

	for(var i=0; i<gantt.config.columns.length; i++){
		var ct = gantt.config.columns[i].template;
		if (ct) copy["_"+i] = ct(obj);
	}
	
	copy.open = obj.$open;
	return copy;
};

})();